package com.fund.common.utils;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.fund.common.enums.WorkdayType;

import java.sql.Date;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HolidayChecker {
    //获取节假日的地址
    public static String HOLIDAY_ADDRESS = "https://timor.tech/api/holiday/year/";
    //假期: 日期 -> 假期名
    static Map<String, String> holiday = new HashMap<>();
    //调休日: 日期 -> 为什么调休
    static Map<String, String> extraWorkDay = new HashMap<>();

    public static Boolean getYearHoliday(String year) {
        try {
            //获取节假日
            String result = HttpUtil.get(HOLIDAY_ADDRESS + year);
            JSONObject entries = JSONUtil.parseObj(result);
            JSONObject holidayMap = entries.getJSONObject("holiday");
            if (holidayMap.isEmpty()){
                return false;
            }

            //遍历holiday的value
            for (Map.Entry<String, Object> entry : holidayMap.entrySet()) {
                String value = entry.getValue().toString();
                JSONObject jsonObject = JSONUtil.parseObj(value);
                if(jsonObject.get("holiday").equals(true)){
                    holiday.put(jsonObject.get("date").toString(),jsonObject.get("name").toString());
                }else {
                    extraWorkDay.put(jsonObject.get("date").toString(),jsonObject.get("name").toString());
                }
            }

        }catch (Exception e){
            e.printStackTrace();
        }
        return true;
    }

    public static WorkdayType getWorkdayType(String year, String date, StringBuilder remark) {
        Boolean yearHoliday = getYearHoliday(year);
        if(!yearHoliday){
            throw new RuntimeException("该年份节假日信息不可用");
        }
        //如果包含在holiday列表中则直接返回holiday
        if(holiday.containsKey(date)){
            remark.append(holiday.get(date));
            return WorkdayType.HOLIDAY;
        }
        //如果包含在extra中直接返回workday
        if(extraWorkDay.containsKey(date)){
            remark.append(extraWorkDay.get(date));
            return WorkdayType.WORKDAY;
        }
        //其余情况按照正常周安排来定
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(date, formatter);
        DayOfWeek dayOfWeek = localDate.getDayOfWeek();
        if(dayOfWeek == DayOfWeek.SUNDAY || dayOfWeek == DayOfWeek.SATURDAY){
            return WorkdayType.WEEKEND;
        }else return WorkdayType.WORKDAY;

    }

}
